package edu.service.impl;

import edu.service.PermissionService;
import edu.vo.Permission;
import edu.repository.PermissionRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class PermissionServiceImpl implements PermissionService {

    private final PermissionRepository permissionRepository;

    public PermissionServiceImpl(PermissionRepository permissionRepository) {
        this.permissionRepository = permissionRepository;
    }

    @Override
    public Permission savePermission(Permission permission) {
        return permissionRepository.save(permission);
    }

    @Override
    public Optional<Permission> getPermissionById(Integer id) {
        return permissionRepository.findById(id);
    }

    @Override
    public List<Permission> getAllPermissions() {
        return permissionRepository.findAll();
    }

    @Override
    public void deletePermissionById(Integer id) {
        permissionRepository.deleteById(id);
    }

    @Override
    public Permission updatePermission(Integer id, Permission permission) {
        return permissionRepository.findById(id)
                .map(existingPermission -> {
                    existingPermission.setText(permission.getText());
                    existingPermission.setType(permission.getType());
                    existingPermission.setUrl(permission.getUrl());
                    existingPermission.setPercode(permission.getPercode());
                    existingPermission.setParentid(permission.getParentid());
                    existingPermission.setSortstring(permission.getSortstring());
                    existingPermission.setAvailable(permission.getAvailable());
                    return permissionRepository.save(existingPermission);
                })
                .orElse(null);
    }
}